import json
from pyexpat.errors import messages
from wsgiref import headers
import logging
from typing import Dict, Any, Optional
import requests
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

class  coolApkAPI:
    def __init__(self,headers):
        self.headers = headers # 抓包的来的请求头
        self.uid = headers["Cookie"].split(";")[0].split("=")[1] # 从请求头中获取用户 id

    def user_profile(self) -> Optional[Dict[str, Any]]:
        """
        获取用户信息并存入缓存文件中

        Returns:
            Optional[Dict[str, Any]]: 返回解析后的用户信息JSON数据，如果出错则返回None

        Raises:
            ValueError: 当UID无效时
            requests.RequestException: 当请求失败时
            json.JSONDecodeError: 当JSON解析失败时
            IOError: 当文件写入失败时
        """
        url = "https://api.coolapk.com/v6/user/profile"

        try:
            # 参数校验
            if not hasattr(self, 'uid') or not self.uid:
                raise ValueError("UID不能为空")
            if not isinstance(self.uid, (str, int)):
                raise ValueError("UID必须是字符串或整数类型")

            params = {'uid': str(self.uid)}

            logger.info(f"开始请求用户信息，UID: {self.uid}")

            # 设置10秒超时
            response = requests.get(
                url,
                params=params,
                headers=self.headers,
                verify=False,
                timeout=10
            )

            # 检查响应状态
            response.raise_for_status()

            # 尝试解析JSON
            try:
                user_data = response.json()
            except json.JSONDecodeError as e:
                logger.error(f"用户信息JSON解析失败: {e}")
                raise

            logger.info("成功获取到用户信息")

            # 写入文件
            try:
                with open('user_profile.json', 'w', encoding='utf-8') as f:
                    json.dump(user_data, f, ensure_ascii=False, indent=4)
                logger.info("用户信息成功写入缓存文件")
            except IOError as e:
                logger.error(f"用户信息文件写入失败: {e}")
                raise

            # 调试用日志（生产环境可注释掉）
            logger.debug(f"用户信息原始响应: {response.text}")

            return user_data

        except requests.RequestException as e:
            logger.error(f"请求用户信息失败: {e}")
            raise
        except Exception as e:
            logger.error(f"获取用户信息时发生未知错误: {e}")
            raise

    def dataList(self) -> Optional[Dict[str, Any]]:
        """
        抓取薅羊毛小分队最新的一页信息，并写入缓存中

        Returns:
            Optional[Dict[str, Any]]: 返回解析后的JSON数据，如果出错则返回None

        Raises:
            ValueError: 当参数无效时
            requests.RequestException: 当请求失败时
            json.JSONDecodeError: 当JSON解析失败时
            IOError: 当文件写入失败时
        """
        url = "https://api.coolapk.com/v6/page/dataList"
        params = {
            'url': "/page?url=/topic/tagFeedList?cacheExpires=60&type=feed&id=23257&title=%E8%96%85%E7%BE%8A%E6%AF%9B%E5%B0%8F%E5%88%86%E9%98%9F&sortField=dateline_desc",
            'title': "最新",
            'page': "1"
        }

        try:
            # 参数校验
            if not all(isinstance(v, str) for v in params.values()):
                raise ValueError("所有参数值必须是字符串类型")
            logger.info(f"开始请求API: {url}")
            response = requests.get(
                url,
                params=params,
                headers=self.headers,
                verify=False,
                timeout=10  # 添加超时设置
            )

            # 检查响应状态
            response.raise_for_status()

            # 尝试解析JSON
            try:
                data = response.json()
            except json.JSONDecodeError as e:
                logger.error(f"JSON解析失败: {e}")
                raise

            logger.info("成功获取到帖子数据")

            # 写入文件
            try:
                with open('dataList.json', 'w', encoding='utf-8') as f:
                    json.dump(data, f, ensure_ascii=False, indent=4)
                logger.info("数据成功写入缓存文件")
            except IOError as e:
                logger.error(f"文件写入失败: {e}")
                raise

            return data

        except requests.RequestException as e:
            logger.error(f"请求失败: {e}")
            raise
        except Exception as e:
            logger.error(f"发生未知错误: {e}")
            raise

    def posts_like(self, postId: str) -> Dict[str, Any]:
        """
        点赞指定帖子

        Args:
            postId (str): 要点赞的帖子ID

        Returns:
            Dict[str, Any]: 返回API的完整响应数据

        Raises:
            ValueError: 当postId无效时
            requests.RequestException: 当请求失败时
        """
        url = "https://api.coolapk.com/v6/feed/like"

        try:
            # 参数校验
            if not postId or not isinstance(postId, str):
                error_msg = "帖子ID必须是非空字符串"
                logger.error(error_msg)
                raise ValueError(error_msg)

            params = {
                'id': postId,
                'detail': "0"
            }

            logger.info(f"尝试点赞帖子，ID: {postId}")

            # 设置请求超时
            response = requests.post(
                url,
                params=params,
                headers=self.headers,
                timeout=10,
                verify=False
            )

            # 检查HTTP状态码
            response.raise_for_status()

            # 解析响应数据
            result = response.json()

            # 根据API返回状态处理结果
            if result.get('data'):
                logger.info(f"成功点赞帖子 ID: {postId}")
                print(f"👍 点赞成功！当前点赞数: {result.get('data', {}).get('count', '未知')}")
            else:
                error_code = result.get('error', '未知')
                error_msg = result.get('message', '未知错误')
                logger.warning(f"点赞失败 ID:{postId} 代码:{error_code} 信息:{error_msg}")
                print(f"⚠️ 操作失败: {error_msg} (错误代码: {error_code})")

            return result

        except requests.RequestException as e:
            error_msg = f"网络请求失败: {str(e)}"
            logger.error(error_msg)
            print(f"❌ {error_msg}")
            raise
        except ValueError as e:
            logger.error(f"参数错误: {str(e)}")
            print(f"❌ {str(e)}")
            raise
        except Exception as e:
            error_msg = f"发生未知错误: {str(e)}"
            logger.error(error_msg)
            print(f"❌ {error_msg}")
            raise

    def posts_reply(self, postId: str, message: str) -> Dict[str, Any]:
        """
        回复指定帖子

        Args:
            postId (str): 要回复的帖子ID
            message (str): 回复内容

        Returns:
            Dict[str, Any]: 返回API的完整响应数据

        Raises:
            ValueError: 当参数无效时
            requests.RequestException: 当请求失败时
        """
        url = "https://api.coolapk.com/v6/feed/reply"

        try:
            # 参数校验
            if not postId or not isinstance(postId, str):
                error_msg = "帖子ID必须是非空字符串"
                logger.error(error_msg)
                raise ValueError(error_msg)

            if not message or not isinstance(message, str):
                error_msg = "回复内容不能为空"
                logger.error(error_msg)
                raise ValueError(error_msg)

            params = {
                'id': postId,
                'type': "feed"
            }

            payload = {
                'message': message
            }

            logger.info(f"尝试回复帖子 ID: {postId}，内容: {message[:20]}...")  # 只记录前20个字符

            # 设置请求超时
            response = requests.post(
                url,
                params=params,
                data=payload,
                headers=self.headers,
                verify=False,
                timeout=10
            )

            # 检查HTTP状态码
            response.raise_for_status()

            # 解析响应数据
            result = response.json()

            # 根据API返回状态处理结果
            if result.get('data').get('fid') == int(postId):
                logger.info(f"成功回复帖子 ID: {postId}")
                print(f"💬 回复成功！")
                if 'data' in result and 'replyid' in result['data']:
                    print(f"  回复ID: {result['data']['replyid']}")
            else:
                error_code = result.get('error', '未知')
                error_msg = result.get('message', '未知错误')
                logger.warning(f"回复失败 ID:{postId} 代码:{error_code} 信息:{error_msg}")
                print(f"⚠️ 回复失败: {error_msg} (错误代码: {error_code})")

            return result

        except requests.RequestException as e:
            error_msg = f"网络请求失败: {str(e)}"
            logger.error(error_msg)
            print(f"❌ {error_msg}")
            raise
        except ValueError as e:
            logger.error(f"参数错误: {str(e)}")
            print(f"❌ {str(e)}")
            raise
        except Exception as e:
            error_msg = f"发生未知错误: {str(e)}"
            logger.error(error_msg)
            print(f"❌ {error_msg}")
            raise

if __name__ == '__main__':
    headers = {
        'User-Agent': "Dalvik/2.1.0 (Linux; U; Android 12; PHN110 Build/W528JS) (#Build; OPPO; PHN110; W528JS release-keys; 12) +CoolMarket/15.3.1-2505201-universal",
        'Connection': "Keep-Alive",
        'Accept-Encoding': "gzip",
        'X-Requested-With': "XMLHttpRequest",
        'X-Sdk-Int': "32",
        'X-Sdk-Locale': "zh-CN",
        'X-App-Id': "com.coolapk.market",
        'X-App-Token': "v3JDJ5JDEwJE5qZ3pabUl6WkRVdll6QTVOV1JsTmVFMzFpbC5TZ3BqVGhPLlNMaGxTLnRUS3FWRjBmRjhp",
        'X-App-Version': "15.3.1",
        'X-App-Code': "2505201",
        'X-Api-Version': "15",
        'X-App-Device': "wGb15GI7MXeltWLlNXYlxWZyByUKhjM1cFI7ATMx4ESQByOPBFUPByOPBFUPByOgsDI7AyO4cGdpJXb31mVFRmY1MmRtMUM0l0SoZ0a0smcqpnUx5meXVFR",
        'X-Dark-Mode': "0",
        'X-App-Channel': "coolapk",
        'X-App-Mode': "universal",
        'X-App-Supported': "2505201",
        'Cookie': "uid=2764811; username=%E5%96%8A%E6%88%91%E8%96%85%E7%BE%8A%E6%AF%9B; token=f630750frDUFKJ_st042RuMSWRY5TsLbQ6kxmNbOdrjIOSPcNkEdwLOzWUSOd8QeIoZiBXkcIl5T54uakjRt5nyJkBBm4n2s4oe7AAXAywmVLmdjUw0xUzKZIaSesVsrXYYLi-0bwlbGD-h5LLjoiKGfsNi9x14TQ2ok6ruT2J-6tc0gbLU8FEXF7rErgCf0-cUQp1vUHpbdw6RIzo08s40Pxn2RsA; ddid=f60682b0-47d0-4f54-aab3-c4374b3d6a00"
    }
    # api = coolApkAPI(headers)
    # api.user_profile() # 获取用户信息
    # api.dataList() # 获取用户信息
    # api.posts_like("65228329")
    # api.posts_reply("65229299","插眼123")